package com.siblings.loan.ui.steps.view

import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.base.utils.DensityUtils
import com.lib.base.utils.log.LogHelper
import com.siblings.loan.R
import com.siblings.loan.databinding.ItemStepCommonBinding
import com.siblings.loan.http.ApiService.addCommonParams
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.steps.act.SibStepsAct
import com.siblings.loan.ui.steps.adapter.SibStepCommonAdapter
import com.siblings.loan.utils.decoration.LinearSpacingItemDecoration
import com.siblings.loan.utils.dialog.BirthdayDialog
import com.siblings.loan.utils.dialog.StepCommonPopup
import com.siblings.loan.utils.event.SibEventType
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/10 15:13
 * @Annotation：步骤通用样式
 */
class SibStepCommonView(private val stepAct: SibStepsAct,private val stepData: JSONObject) {
    var binding = ItemStepCommonBinding.inflate(stepAct.layoutInflater)

    @SuppressLint("StaticFieldLeak")
    private var commonAdapter: SibStepCommonAdapter? = null
    private var mSelectPosition = -1
    //出生日期选择
    private var birthdayDialog: BirthdayDialog? = null

    init {
        initSibCommonViews()
        initSibCommonListener()
    }

    /**
     * 通用样式
     */
    fun includeSibStepCommonView(): View {
        return binding.root
    }

    /**
     * 初始化Views
     */
    private fun initSibCommonViews(){
        val layoutManager = LinearLayoutManager(stepAct)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        val topDecoration = DensityUtils.dp2px(14f)
        binding.recyclerView.addItemDecoration(LinearSpacingItemDecoration(0,0,0,topDecoration))
        commonAdapter = SibStepCommonAdapter(binding.recyclerView)
        binding.recyclerView.adapter = commonAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        commonAdapter!!.setOnItemChildClickListener { _, childView, position ->
            binding.root.clearFocus()
            mSelectPosition = position
            val item = commonAdapter!!.getItem(position)
            when (item.optString("action")) {
                "DATE_PICK" -> {//时间选择
                    showSibBirthDialog()
                }
                "SELECT" -> {//选择
                    val dataList = arrayListOf<JSONObject>()
                    val dataArray = item.optJSONArray("values")
                    if (dataArray != null) {
                        for (i in 0..<dataArray.length()) {
                            dataList.add(dataArray.optJSONObject(i))
                        }
                    }
                    showSelectPopupwindow(childView, dataList)
                }
            }
        }
    }

    /**
     * 初始化事件监听
     */
    private fun initSibCommonListener(){
        //提交
        binding.btnNext.setOnClickListener {
            if (!isAllowCommonSubmit()){
                stepAct.showSibTipsDialog(stepData.optString("stepTitle"))
                return@setOnClickListener
            }

            val params = JSONObject().addCommonParams().apply {
                put("path", stepData.optString("apiUrl").replace("/",""))
            }
            for (i in 0..<commonAdapter!!.itemCount){
                val item = commonAdapter!!.getItem(i)
                if (item.has("selectItem")){
                    val selectItem = item.optJSONObject("selectItem")
                    if (selectItem != null){
                        params.put(item.optString("paramName"),selectItem.optString("value"))
                    }
                }
            }
            LogHelper.e(">>>>>>submit data >>>>>>>$params")
            stepAct.mvpPresenter.onSibSubmitProcessAction(params)

            HttpHelper.addSibEventAction(String.format(SibEventType.CLICK.SIB_CLICK_STEP_XX_NEXT, stepData.optString("stepTitle")),"")
        }
    }

    /**
     * 设置数据
     */
    fun setSibCommonData(dataList: ArrayList<JSONObject>){
        commonAdapter!!.data = dataList
    }

    /**
     * 通用类型列表
     * 检查是否填写完整
     * 当且仅当 isMust=”NO“为非必填
     */
    private fun isAllowCommonSubmit(): Boolean{
        //是否允许提交
        var isAllow = true
        for (i in 0..<commonAdapter!!.itemCount){
            val item = commonAdapter!!.getItem(i)
            //存在 isMust && isMust == ”NO“  非必填
            if (item.has("isMust") && item.optString("isMust") == "NO"){
                continue
            }
            //必填 && 没有内容 || 内容为空
            if (!item.has("selectItem") || item.optJSONObject("selectItem")?.optString("value")!!.isEmpty()){
                isAllow = false
                break
            }
        }
        return isAllow
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View,dataList: ArrayList<JSONObject>){
        val selectPopup = StepCommonPopup(stepAct)
        selectPopup.setWindowWidth(view.width + DensityUtils.dp2px(10f))
        selectPopup.setSelectItemListener(object : StepCommonPopup.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                val item = commonAdapter!!.getItem(mSelectPosition)
                item.put("selectItem",data)
                commonAdapter!!.notifyItemChanged(mSelectPosition)

                HttpHelper.addSibEventAction(String.format(SibEventType.CLICK.SIB_CLICK_STEP_XX_SELECT,item.optString("paramName")),data!!.optString("value"))
            }
            //关闭监听
            override fun onDismissListener() {
            }
        })
        selectPopup.show(view, stepAct.binding.root)
        selectPopup.setBrandList(dataList)
    }

    /**
     * 选择出生日期
     */
    private fun showSibBirthDialog(){
        if (birthdayDialog == null){
            birthdayDialog = BirthdayDialog(stepAct,"",object : BirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    //可根据需要自行截取数据显示
                    val item = commonAdapter!!.getItem(mSelectPosition)
                    val obj = JSONObject()
                    obj.put("title",selectDate.optString("showDate"))
                    obj.put("value",selectDate.optString("subDate"))
                    item.put("selectItem",obj)
                    commonAdapter!!.notifyItemChanged(mSelectPosition)

                    HttpHelper.addSibEventAction(String.format(SibEventType.CLICK.SIB_CLICK_STEP_XX_SELECT,item.optString("paramName")),selectDate.optString("subDate"))
                }
            })
        }
        birthdayDialog!!.show()
    }

    fun onDestroy(){
        if (commonAdapter != null){
            commonAdapter = null
        }
        mSelectPosition = -1
        if (birthdayDialog != null){
            birthdayDialog = null
        }
    }
}